package com.dididoctor.patient.Activity;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.telephony.TelephonyManager;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.WindowManager;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.dididoctor.patient.Activity.Doctor.ForumModuleFragment;
import com.dididoctor.patient.Activity.Service.ServiceDetail.ServiceDetailActivity;
import com.dididoctor.patient.Activity.Usercentre.Consume.UserConsumeActivity;
import com.dididoctor.patient.Activity.Usercentre.Record.Cases.CasesDetail.CasesDetailActivity;
import com.dididoctor.patient.Activity.Usercentre.Record.Cases.CasesDetailUp.CasesDetailUpActivity;
import com.dididoctor.patient.Activity.Usercentre.Setting.UserSettingActivity;
import com.dididoctor.patient.Activity.Welcome.WelcomeDialog;
import com.dididoctor.patient.Activity.mvp.MainActivity;
import com.dididoctor.patient.Bean.Token;
import com.dididoctor.patient.R;
import com.dididoctor.patient.Ui.cityList.CityBean;
import com.dididoctor.patient.Utils.SharedPreferencesUtils;
import com.dididoctor.patient.Utils.Util;
import com.dididoctor.patient.WYY.CustomAttachmentType;
import com.dididoctor.patient.WYY.DemoCache;
import com.dididoctor.patient.WYY.SessionHelper;
import com.dididoctor.patient.WYY.SystemUtil;
import com.dididoctor.patient.WYY.Timely.TimelyAttachment;
import com.netease.nim.uikit.ImageLoaderKit;
import com.netease.nim.uikit.NimUIKit;
import com.netease.nim.uikit.cache.FriendDataCache;
import com.netease.nim.uikit.cache.NimUserInfoCache;
import com.netease.nim.uikit.cache.TeamDataCache;
import com.netease.nim.uikit.contact.ContactProvider;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MessageNotifierCustomization;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.uinfo.UserInfoProvider;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import org.litepal.LitePalApplication;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;


public class GlobalParams extends LitePalApplication {
    public static ArrayList<String> listPath = new ArrayList<String>();// 存放图片的路径的集合
    /**
     * 代理ip
     */
    public static String PROXY_IP = "";
    /**
     * 代理端口
     */
    public static int PROXY_PORT = 0;
    /**
     * 屏幕宽度
     */
    public static int WIN_WIDTH = 0;

    /**
     * 用户注销
     */
    public static void Logout() {
    }

    /**
     * 获取设备信息
     */
    public static Context MAIN_CONTEXT = null;
    public static String uuid;
    public static boolean isLocking = true;
    public static String unread_message_count = "";
    public static boolean success = false;
    public static int IMAGE_INDEX = 0;


    public TextView mLocationResult, logMsg;
    public TextView trigger, exit;
    public Vibrator mVibrator;
    private static Context context = null;
    private PendingIntent intent;
    private static final Random random = new Random(System.currentTimeMillis());
    private NotificationManager manager;
    private Notification notification;
    private Vibrator mVibrator01;  //声明一个振动器对象
    //baidu定位
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    //位置信息
    private String longitude, latitude, cityCode;
    @Override
    public void onCreate() {

        super.onCreate();
        // ImageLoaderConfiguration config = new
        // ImageLoaderConfiguration.Builder(
        // getApplicationContext())
        // .threadPriority(Thread.NORM_PRIORITY - 2)// 设置线程的优先级
        // .denyCacheImageMultipleSizesInMemory()//
        // 当同一个Uri获取不同大小的图片，缓存到内存时，只缓存一个。默认会缓存多个不同的大小的相同图片
        // .discCacheFileNameGenerator(new Md5FileNameGenerator())// 设置缓存文件的名字
        // .discCacheFileCount(60)// 缓存文件的最大个数
        // .tasksProcessingOrder(QueueProcessingType.LIFO)// 设置图片下载和显示的工作队列排序
        // .build();
        //
        // // Initialize ImageLoader with configuration
        // ImageLoader.getInstance().init(config);

        // CrashHandler crashHandler = CrashHandler.getInstance();
        // crashHandler.init(getApplicationContext());
        // 定位


        instance = this;
        // 错误日志上传，开发时关闭，上线时打开
//		 UncaughtException crashHandler = UncaughtException.getInstance();
//		 crashHandler.init();
        context = getApplicationContext();
        DemoCache.setContext(this);

        initLocation();
        // SDK初始化（启动后台服务，若已经存在用户登录信息， SDK 将完成自动登录）
        NIMClient.init(this, loginInfo(), options());
        if (inMainProcess()) {
            manager = (NotificationManager) getContext()
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            // 初始化UIKit模块
            initUIKit();
            //自定义消息接收器
            NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(new Observer<CustomNotification>() {
                @Override
                public void onEvent(CustomNotification message) {
//                    "app": "1",
//                            "webUrl": "https://www.baidu.com/",
//                            "picUrl": "http://192.168.1.181:8080/doctor/upload/bankLogo/1.png",
//                            "type": "1", 活动是1诊断书是2咨询过期是3
//                            "msg": "在线咨询7.5折"


//                    {
//                        "app": "1",
//                            "accid": "2",
//                            "recId": "1",
//                            "type": "7",
//                            "msg": "本次电话咨询已结束"
//                    }
                    if (message.getSessionType() == SessionTypeEnum.P2P) {
                        String content = message.getContent();
                        Map<String, Object> pushPayload = message.getPushPayload();
                        if (pushPayload != null) {
                            String prapp = pushPayload.get("app").toString();

                            if ("1".equals(prapp)) {
                                String prtype = pushPayload.get("type").toString();
                                if ("1".equals(prtype)) {
//                                    内容:活动内容(如:迎五一，一毛钱签约医生活动开始了，赶快去签约吧)
//                                    点击:活动详情界面
                                    String des = pushPayload.get("msg").toString();
                                    String type = pushPayload.get("type").toString();
                                    String webUrl = pushPayload.get("webUrl").toString();
                                    String picUrl = pushPayload.get("picUrl").toString();
                                    SharedPreferencesUtils.setParam(getContext(),"event_isShow","1");
                                    SharedPreferencesUtils.setParam(getContext(),"event_webUrl",webUrl);
                                    SharedPreferencesUtils.setParam(getContext(),"event_picUrl",picUrl);
                                    //点击通知栏跳转的界面设置
                                    Intent intent1 = null;
                                    intent1 = new Intent(getContext(), ServiceDetailActivity.class);
                                    intent1.putExtra("webUrl", webUrl);
                                    Log.e("WEB_URL", webUrl);
                                    //延迟意图设置进入通知栏用
                                    intent = PendingIntent.getActivity(getContext(), random.nextInt(),
                                            intent1, PendingIntent.FLAG_UPDATE_CURRENT);
                                    //发送通知
                                    sendNotification(des, intent);
                                }else  if ("2".equals(prtype)){
//                                    内容:您于4月21日 18:24分咨询的问题，医生已经为您下达诊疗建议，可以到个人中心我的病历中查看
//                                    点击:病历详情页
                                    String recType = pushPayload.get("recType").toString();
                                    String recId = pushPayload.get("recId").toString();
                                    Intent intent2 = null;
                                    if ("2".equals(recType)) {//自传
                                        intent2= new Intent(context, CasesDetailUpActivity.class);
                                        intent2.putExtra("recId", recId);
                                    } else if ("1".equals(recType)){//医生
                                        intent2 = new Intent(context, CasesDetailActivity.class);
                                        intent2.putExtra("recId", recId);
                                        intent2.putExtra("type", recType);
                                    }else{
                                        intent2 = new Intent();
                                    }
                                    //延迟意图设置进入通知栏用
                                    intent = PendingIntent.getActivity(context, random.nextInt(),
                                            intent2, PendingIntent.FLAG_UPDATE_CURRENT);

                                    String  des = pushPayload.get("msg").toString();
                                    //发送通知
                                    sendNotification(des, intent);
                                } else  if ("3".equals(prtype)){
//                                    内容:很抱歉，您于4月21日 18:24分咨询的问题，由于特殊原因医生没能及时回答，您可以在消费记录中申请退款，或者通过练习客服退款
//                                    点击:消费记录列表页
                                    Intent intent3 = new Intent(context, UserConsumeActivity.class);
                                    intent = PendingIntent.getActivity(context, random.nextInt(),
                                            intent3, PendingIntent.FLAG_UPDATE_CURRENT);

                                    String  des = pushPayload.get("msg").toString();
                                    //发送通知
                                    sendNotification(des, intent);
                                } else  if ("4".equals(prtype)){
//                                  内容:您于4月21日 18:24分预约电话服务已经结束，医生已经对您下达诊疗建议，快去看看吧
//                                    点击:跳转病历详情页面
                                     String recType = pushPayload.get("recType").toString();
                                    String recId = pushPayload.get("recId").toString();
                                    Intent intent4 = null;
                                    if ("2".equals(recType)) {//自传
                                        intent4= new Intent(context, CasesDetailUpActivity.class);
                                        intent4.putExtra("recId", recId);
                                    } else if ("1".equals(recType)){//医生
                                        intent4 = new Intent(context, CasesDetailActivity.class);
                                        intent4.putExtra("recId", recId);
                                        intent4.putExtra("type", recType);
                                    }else{
                                        intent4 = new Intent();
                                    }
                                    //延迟意图设置进入通知栏用
                                    intent = PendingIntent.getActivity(context, random.nextInt(),
                                            intent4, PendingIntent.FLAG_UPDATE_CURRENT);

                                    String  des = pushPayload.get("msg").toString();
                                    //发送通知
                                    sendNotification(des, intent);
                                }else if ("7".equals(prtype)) {
                                    //7  发送即时电话通知，打完电话后获得这个通知去发自定义消息
                                    String prmsg = pushPayload.get("msg").toString();
                                    String accid = pushPayload.get("accid").toString();
                                    String recId = pushPayload.get("recId").toString();
                                    String diseId = pushPayload.get("diseId").toString();
                                    TimelyAttachment attachment = new TimelyAttachment(CustomAttachmentType.TIMELYPHONE);
                                    attachment.setPatientName(Token.getName());
                                    String dateString = Token.getBirth();
                                    String[] split = dateString.split("-");
                                    Date date = null;
                                    int age = 0;
                                    if (split != null && split.length > 0) {
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                                        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy");
                                        String Curvedate = sDateFormat.format(new Date());
                                        age = Integer.parseInt(Curvedate) - Integer.parseInt(split[0]);
                                    }
                                    if (age > 0) {
                                        attachment.setAge(age + "");
                                    } else {
                                        attachment.setAge("0");
                                    }

                                    attachment.setIllName("");
                                    attachment.setPatientHeadPic(Token.getHeadPic());
                                    attachment.setRecId(recId);
                                    attachment.setDisId(diseId);
                                    attachment.setSuggestion("");
                                    attachment.setSuggestionResult("");
                                    attachment.setMessageAttachType(CustomAttachmentType.TIMELYPHONE + "");
                                    attachment.setSex(Token.getSex());
                                    IMMessage messages;

                                    messages = MessageBuilder.createCustomMessage(accid, SessionTypeEnum.P2P, "", attachment);
                                    NIMClient.getService(MsgService.class).sendMessage(messages, true);
                                }else  if ("6".equals(prtype)){
//                                    内容:您于4月21日 18:24申请的图文咨询/电话预约退款失败，您可以通过拨打客服电话来申请退款
//                                    点击:拨打客服电话
                                    Intent intent6 = new Intent(context, UserSettingActivity.class);
                                    //延迟意图设置进入通知栏用
                                    intent = PendingIntent.getActivity(context, random.nextInt(),
                                            intent6, PendingIntent.FLAG_UPDATE_CURRENT);

                                    String  des = pushPayload.get("msg").toString();
                                    //发送通知
                                    sendNotification(des, intent);
                                } else  if ("8".equals(prtype)){
//                                 内容:您于2016-5-1 12:00提交的电话预约咨询服务已经过期 如您不想继续等待医生来电 可以在消费记录中申请退款
                                    Intent intent8 = new Intent();
                                    intent = PendingIntent.getActivity(context, random.nextInt(),
                                            intent8, PendingIntent.FLAG_UPDATE_CURRENT);

                                    String  des = pushPayload.get("msg").toString();
                                    //发送通知
                                    sendNotification(des, intent);
                                }else if ("9".equals(prtype)){
                                    String title = pushPayload.get("msg").toString();
                                    String des = pushPayload.get("content").toString();
                                    WelcomeDialog wd = new WelcomeDialog(getApplicationContext(),title,des);
                                    wd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);  //窗口可以获得焦点，响应操作
                                    wd.show();

                                    Intent intent9 = new Intent();
                                    //延迟意图设置进入通知栏用
                                    intent = PendingIntent.getActivity(context, random.nextInt(),
                                            intent9 , PendingIntent.FLAG_UPDATE_CURRENT);

                                    //发送通知
                                    sendNotification(title, intent);
                                }else {
                                    String des = pushPayload.get("msg").toString();
                                    Intent intentsj = new Intent();
                                    intent = PendingIntent.getActivity(getContext(), random.nextInt(),
                                            intentsj, PendingIntent.FLAG_UPDATE_CURRENT);
                                    //发送通知
                                    sendNotification(des, intent);
                                }
                            }
                        }
                    }
                }
            }, true);

        }
    }


    //baidu定位
    private void initLocation() {
        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }


    //baidu定位
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            DecimalFormat df = new DecimalFormat("#.000000");
            latitude = Util.toString(df.format(location.getLatitude()));
            SharedPreferencesUtils.setParam(getContext(),"Globallatitude",latitude);
            longitude = Util.toString(df.format(location.getLongitude()));
            SharedPreferencesUtils.setParam(getContext(),"Globallongitude",longitude);
            cityCode = Util.toString(location.getCityCode());
            SharedPreferencesUtils.setParam(getContext(),"GlobalcityCode",cityCode);
        }
    }

    private void sendNotification(String des, PendingIntent intent) {
        notification = new Notification();
        notification.icon = R.drawable.applogos; // 显示的图标
        notification.defaults = Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_LIGHTS;
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.when = System.currentTimeMillis();
        notification.tickerText = des;
        //设置标题  和内容
        String title = "滴滴医生";


        /** 设置通知消息 */
        //需要标题和内容   title通知的标题  des通知的内容
        notification.setLatestEventInfo(getContext(), title, des, intent);

        manager.notify(0, notification);
        //消息振动器
        mVibrator01 = (Vibrator) getContext().getSystemService(Service.VIBRATOR_SERVICE);
        mVibrator01.vibrate(new long[]{100, 10, 100, 1000}, -1);
    }


    private void initUIKit() {
        // 初始化，需要传入用户信息提供者
        NimUIKit.init(this, infoProvider, contactProvider);

        // 会话窗口的定制初始化。
        SessionHelper.init();
    }

    private ContactProvider contactProvider = new ContactProvider() {
        @Override
        public List<UserInfoProvider.UserInfo> getUserInfoOfMyFriends() {
            List<NimUserInfo> nimUsers = NimUserInfoCache.getInstance().getAllUsersOfMyFriend();
            List<UserInfoProvider.UserInfo> users = new ArrayList<>(nimUsers.size());
            if (!nimUsers.isEmpty()) {
                users.addAll(nimUsers);
            }

            return users;
        }

        @Override
        public int getMyFriendsCount() {
            return FriendDataCache.getInstance().getMyFriendCounts();
        }

        @Override
        public String getUserDisplayName(String account) {
            return NimUserInfoCache.getInstance().getUserDisplayName(account);
        }
    };

    public boolean inMainProcess() {
        String packageName = getPackageName();
        String processName = SystemUtil.getProcessName(this);
        return packageName.equals(processName);
    }

    public static Context getContext() {
        return context;
    }

    // 如果返回值为 null，则全部使用默认参数。
    private SDKOptions options() {
        SDKOptions options = new SDKOptions();

        // 如果将新消息通知提醒托管给 SDK 完成，需要添加以下配置。否则无需设置。
        StatusBarNotificationConfig config = new StatusBarNotificationConfig();
        config.notificationEntrance = MainActivity.class; // 点击通知栏跳转到该Activity
        config.notificationSmallIconId = R.drawable.applogos;
        options.statusBarNotificationConfig = config;

        // 配置保存图片，文件，log 等数据的目录
        // 如果 options 中没有设置这个值，SDK 会使用下面代码示例中的位置作为 SDK 的数据目录。
        // 该目录目前包含 log, file, image, audio, video, thumb 这6个目录。
        // 如果第三方 APP 需要缓存清理功能， 清理这个目录下面个子目录的内容即可。
        String sdkPath = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/nim";
        options.sdkStorageRootPath = sdkPath;

        // 配置是否需要预下载附件缩略图，默认为 true
        options.preloadAttach = true;
        DemoCache.setNotificationConfig(config);
        // 配置附件缩略图的尺寸大小。表示向服务器请求缩略图文件的大小
        // 该值一般应根据屏幕尺寸来确定， 默认值为 Screen.width / 2
//        options.thumbnailSize = ${Screen.width} / 2;

        // 用户资料提供者, 目前主要用于提供用户资料，用于新消息通知栏中显示消息来源的头像和昵称
        options.userInfoProvider = new UserInfoProvider() {
            @Override
            public UserInfo getUserInfo(String account) {
                return null;
            }

            @Override
            public int getDefaultIconResId() {
                return R.drawable.def_user;
            }

            @Override
            public Bitmap getTeamIcon(String tid) {
                return null;
            }

            @Override
            public Bitmap getAvatarForMessageNotifier(String account) {
                return null;
            }

            @Override
            public String getDisplayNameForMessageNotifier(String account, String sessionId,
                                                           SessionTypeEnum sessionType) {
                return null;
            }
        };
        return options;
    }

    // 如果已经存在用户登录信息，返回LoginInfo，否则返回null即可
    private LoginInfo loginInfo() {
        String account = SharedPreferencesUtils.getParam(context, "WYYaccountpatient", "");
        String token = SharedPreferencesUtils.getParam(context, "WYYtokenpatient", "");

        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
            DemoCache.setAccount(account.toLowerCase());
            return new LoginInfo(account, token);
        } else {
            return null;
        }
    }

    /**
     * 得到全局唯一UUID
     */
    public static String getUUID(Context context) {

        if (uuid == null || "".equals(uuid)) {
            uuid = UUID.randomUUID().toString().replaceAll("-", "");
        }
        return uuid;

        // uuid = SharedPreferencesUtils.getParam(context, "uuid", "");
        // if(TextUtils.isEmpty(uuid)){
        // uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // SharedPreferencesUtils.setParam(context, "uuid", uuid);
        // }
        // return uuid;
    }

    /**
     * 检测手机号
     *
     * @return
     */
    public static String myphone(Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String tel = tm.getLine1Number();
        return tel;
    }

    public static SpannableStringBuilder errorMsg(String estring) {
        int ecolor = Color.BLACK; // whatever color you want
        ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
        SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
        ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
        return ssbuilder;
    }


    private UserInfoProvider infoProvider = new UserInfoProvider() {
        @Override
        public UserInfo getUserInfo(String account) {
            UserInfo user = NimUserInfoCache.getInstance().getUserInfo(account);
            if (user == null) {
                NimUserInfoCache.getInstance().getUserInfoFromRemote(account, null);
            }

            return user;
        }

        @Override
        public int getDefaultIconResId() {
            return R.drawable.def_user;
        }

        @Override
        public Bitmap getTeamIcon(String teamId) {
            Drawable drawable = getResources().getDrawable(R.drawable.nim_avatar_group);
            if (drawable instanceof BitmapDrawable) {
                return ((BitmapDrawable) drawable).getBitmap();
            }

            return null;
        }

        @Override
        public Bitmap getAvatarForMessageNotifier(String account) {
            /**
             * 注意：这里最好从缓存里拿，如果读取本地头像可能导致UI进程阻塞，导致通知栏提醒延时弹出。
             */
            UserInfo user = getUserInfo(account);
            return (user != null) ? ImageLoaderKit.getNotificationBitmapFromCache(user) : null;
        }

        @Override
        public String getDisplayNameForMessageNotifier(String account, String sessionId, SessionTypeEnum sessionType) {
            String nick = null;
            if (sessionType == SessionTypeEnum.P2P) {
                nick = NimUserInfoCache.getInstance().getAlias(account);
            } else if (sessionType == SessionTypeEnum.Team) {
                nick = TeamDataCache.getInstance().getTeamNick(sessionId, account);
                if (TextUtils.isEmpty(nick)) {
                    nick = NimUserInfoCache.getInstance().getAlias(account);
                }
            }
            // 返回null，交给sdk处理。如果对方有设置nick，sdk会显示nick
            if (TextUtils.isEmpty(nick)) {
                return null;
            }

            return nick;
        }
    };


    @Override
    public void onTerminate() {
        super.onTerminate();
    }


    public static String getDeviceId(Context context) {
        StringBuilder deviceId = new StringBuilder();

        // 渠道标志
        deviceId.append("client");
        try {
            // wifi mac地址
            WifiManager wifi = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            String wifiMac = info.getMacAddress();
            if (!TextUtils.isEmpty(wifiMac)) {
                deviceId.append("wifi");
                deviceId.append(wifiMac);
                return deviceId.toString().replace(":", "").toLowerCase();
            }

            // IMEI（imei）
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String imei = tm.getDeviceId();
            if (!TextUtils.isEmpty(imei)) {
                deviceId.append("imei");
                deviceId.append(imei);
                return deviceId.toString();
            }
            // 序列号（sn）
            String sn = tm.getSimSerialNumber();
            if (!TextUtils.isEmpty(sn)) {
                deviceId.append("sn");
                deviceId.append(sn);
                return deviceId.toString();
            }

            // 如果上面都没有， 则生成一个id：随机码
            uuid = getUUID(context);
            if (!TextUtils.isEmpty(uuid)) {
                deviceId.append("id");
                deviceId.append(uuid);
                return deviceId.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            deviceId.append("id").append(getUUID(context));
        }
        return deviceId.toString();

    }

    private static GlobalParams instance;

    // 单例模式中获取唯一的ExitApplication实例
    public static GlobalParams getInstance() {
        return instance;

    }

    // 遍历所有Activity并finish

    private List<Activity> activityList = new LinkedList<Activity>();

    public List<Activity> getActivityList() {
        return activityList;
    }

    // 添加Activity到容器中
    public void addActivity(Activity activity) {
        activityList.add(activity);
    }

    // 遍历所有Activity并finish

    public void exit() {

        for (Activity activity : activityList) {
            activity.finish();
        }
        // System.exit(0);

    }

    private MessageNotifierCustomization messageNotifierCustomization = new MessageNotifierCustomization() {
        @Override
        public String makeNotifyContent(String nick, IMMessage message) {
            return null; // 采用SDK默认文案
        }

        @Override
        public String makeTicker(String nick, IMMessage message) {
            return null; // 采用SDK默认文案
        }
    };
    public static ArrayList<CityBean> hotCityData = null;
}

